package com.wpf.rounter2function.exception;

import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebExceptionHandler;
import reactor.core.publisher.Mono;

@Component
@Order(-2)
public class ExceptionHandler implements WebExceptionHandler {

    @Override
    public Mono<Void> handle(ServerWebExchange serverWebExchange, Throwable throwable) {

        ServerHttpResponse response = serverWebExchange.getResponse();
        //设置响应头404
        response.setStatusCode(HttpStatus.BAD_REQUEST);
        //设置返回类型
        response.getHeaders().setContentType(MediaType.TEXT_PLAIN);
        String err = getErr(throwable);
        DataBuffer wrap = response.bufferFactory().wrap(err.getBytes());
        return response.writeWith(Mono.just(wrap));
    }

    private String getErr(Throwable throwable) {

        if(throwable instanceof ValidException){
            ValidException e = (ValidException) throwable;
            return e.getKey()+":"+e.getValue();
        }else {
            throwable.printStackTrace();
            return throwable.toString();
        }
    }

}
